package com.zuowei.ycy.user.ui.index;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.and.yzy.frame.util.RetrofitUtils;
import com.and.yzy.frame.view.gradview.GridViewForScrolview;
import com.and.yzy.frame.view.listview.ListViewForScrollView;
import com.baidu.location.BDLocation;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.adapter.GoodInfoAdapter;
import com.zuowei.ycy.user.adapter.IndexSortAdapter;
import com.zuowei.ycy.user.config.UserManger;
import com.zuowei.ycy.user.domain.GoodInfo;
import com.zuowei.ycy.user.domain.IndexResult;
import com.zuowei.ycy.user.domain.IndexSort;
import com.zuowei.ycy.user.http.Merchant;
import com.zuowei.ycy.ui.BaseFgt;
import com.zuowei.ycy.user.util.AppJsonUtil;
import com.zuowei.ycy.user.util.MyLocationUtil;
import com.zuowei.ycy.user.util.PtrInitHelper;
import com.zuowei.ycy.user.view.NotifyingScrollView;
import com.zuowei.ycy.user.view.UriImageHolderView;

import java.util.List;

import butterknife.Bind;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/4/25.
 */
public class IndexFgt extends BaseFgt {

    @Bind(R.id.lv_data)
    ListViewForScrollView mLvData;
    @Bind(R.id.sv_data)
    NotifyingScrollView mScrollView;
    @Bind(R.id.ll_title_address)
    LinearLayout mLayoutAddress;
    @Bind(R.id.ptr_frame)
    PtrFrameLayout mPtrFrame;

    @Bind(R.id.ban_index_title)
    ConvenientBanner mb_title;

    List<IndexResult.AdvertEntity> mBannerImages;
    @Bind(R.id.gv_data)
    GridViewForScrolview forScrolview;
    IndexSortAdapter indexSortAdapter;
    GoodInfoAdapter infoAdapter;
    @Bind(R.id.tv_address)
    TextView mTvAddress;

    @Override
    public int getLayoutId() {
        return R.layout.index_layout;
    }

    @Override
    public void initData() {





        mScrollView.scrollTo(0, 0);
       mLayoutAddress.getBackground().setAlpha(90);
        PtrInitHelper.initPtr(getContext(), mPtrFrame);
        mPtrFrame.disableWhenHorizontalMove(true);
        mPtrFrame.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(final PtrFrameLayout frame) {

                doHttp(RetrofitUtils.createApi(Merchant.class).index(UserManger.getBaiDuLon(), UserManger.getBaiDuLat()), 1);

            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mScrollView, header);
            }
        });


        mScrollView.setOnScrollChangedListener(new NotifyingScrollView.OnScrollChangedListener() {
            @Override
            public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {

                int lHeight = (int) getResources().getDimension(R.dimen.y200);
                if (t <= lHeight) {
                    int progress = (int) (new Float(t) / new Float(lHeight) * 255);
                    if (progress <= 90) {
                        mLayoutAddress.getBackground().setAlpha(90);
                    } else {
                        mLayoutAddress.getBackground().setAlpha(progress);
                    }

                } else {
                    mLayoutAddress.getBackground().setAlpha(255);
                }
            }
        });


        forScrolview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                IndexSort indexSort = (IndexSort) parent.getItemAtPosition(position);

                Bundle bundle = new Bundle();
                bundle.putString("merchant_type_id", indexSort.getMerchant_type_id());
                bundle.putString("merchant_type_name", indexSort.getMerchant_type_name());
                startActivity(GoodSortAty.class, bundle);
            }
        });


        mLvData.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                GoodInfo goodInfo = (GoodInfo) parent.getItemAtPosition(position);

                Bundle bundle = new Bundle();
                bundle.putString("merchant_id", goodInfo.getMerchant_id());
                bundle.putString("shop_name", goodInfo.getShop_name());
                startActivity(BusinessTabAty.class, bundle);
            }
        });

        mb_title.startTurning(5000);


    }

    @Override
    public void onResume() {
        super.onResume();
        //开始自动翻页
        if (mb_title != null)
            mb_title.startTurning(5000);
    }


    @Override
    public void onPause() {
        super.onPause();
        //停止翻页
        if (mb_title != null)
            mb_title.stopTurning();
    }

    @Override
    public boolean setIsInitRequestData() {
        return true;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showLoadingContentDialog();
    }

    @Override
    public void requestData() {

        //开启定位

        MyLocationUtil locationUtil = new MyLocationUtil(getActivity(), new MyLocationUtil.MyLocationListener() {
            @Override
            public void sussessLocation(double lat, double lon, BDLocation location) {

                if (lat > 0&&location.getStreet()!=null) {
                    if ( location.getStreet()==null){
                        mTvAddress.setText("送至:定位有误" );
                    }else {
                        mTvAddress.setText("送至:" + location.getStreet());
                    }

                    UserManger.setBaiDuLat(lat + "");
                    UserManger.setBaiDuLon(lon + "");
                    doHttp(RetrofitUtils.createApi(Merchant.class).index(lat+"", ""+lon), 1);
                }
            }

            @Override
            public void error() {
                mTvAddress.setText("送至:定位有误" );
                doHttp(RetrofitUtils.createApi(Merchant.class).index("117.159644", "39.098411"), 1);
            }
        }, 10);
    }


    @Override
    public void onFailure(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {
        super.onFailure(result, call, response, what);
        mPtrFrame.refreshComplete();

    }

    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {


        IndexResult indexResult = AppJsonUtil.getObject(result, IndexResult.class);


        //广告页

        if (mBannerImages == null) {
            mBannerImages = indexResult.getAdvert();

            mb_title.setPages(new CBViewHolderCreator<UriImageHolderView>() {
                @Override
                public UriImageHolderView createHolder() {
                    return new UriImageHolderView();
                }
            }, mBannerImages)
                    .setPageIndicator(new int[]{R.drawable.shouye_banner, R.drawable.shouye_banner2}, 0)
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
            ;

        } else {

            mBannerImages.clear();
            mBannerImages.addAll(indexResult.getAdvert());
            mb_title.notifyDataSetChanged();

        }


        if (indexSortAdapter == null) {
            indexSortAdapter = new IndexSortAdapter(getActivity(), indexResult.getMerchant_type_list(), R.layout.index_sort_item);
            forScrolview.setAdapter(indexSortAdapter);
        } else {
            indexSortAdapter.removeAll();
            indexSortAdapter.addAll(indexResult.getMerchant_type_list());
        }


        if (infoAdapter == null) {
            infoAdapter = new GoodInfoAdapter(getActivity(), indexResult.getMerchant_list(), R.layout.index_good_item);
            mLvData.setAdapter(infoAdapter);
        } else {
            infoAdapter.removeAll();
            infoAdapter.addAll(indexResult.getMerchant_list());
        }


        mPtrFrame.refreshComplete();
        super.onSuccess(result, call, response, what);

    }

    @Override
    public void onError(Call<ResponseBody> call, Throwable t, int what) {
        super.onError(call, t, what);
        mPtrFrame.refreshComplete();
    }


}
